package top.lywivan.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class MapperUtil {
    private MapperUtil(){}
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> threadLocal=new ThreadLocal<>();
    static {
        try {
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("SqlMapConfig.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static SqlSession getSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession==null){
            sqlSession=sqlSessionFactory.openSession();
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }

    public static<T> T getMapper(Class<T> clazz){
        return getSqlSession().getMapper(clazz);
    }

    public static void close(){
        getSqlSession().close();
        threadLocal.remove();
    }

    public static void commitAndClose(){
        getSqlSession().commit();
        close();
        threadLocal.remove();
    }

    public static void rollbackAndClose(){
        getSqlSession().rollback();
        close();
        threadLocal.remove();
    }
}
